/**
 * 
 */
package dk.itu.mobile.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * @author group-02
 * TaskClient sends request to TaskServer using UDP protocol 
 *
 */
public class TaskClient {
	private int port;
	private static InetAddress address;
	private static DatagramSocket socket;
	private static DatagramPacket packet;
	private static byte[] sendBuffer;
	private static byte[] recieveBuffer;

	public TaskClient(String name){

		this.port = 4445;
		try {
			address = InetAddress.getLocalHost();
		} catch( UnknownHostException ukhe) {
			ukhe.printStackTrace();
		}	
		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		TaskClient C1 = new TaskClient("Client1");
		TaskClient C2 = new TaskClient("Client2");
		TaskClient C3 = new TaskClient("Client3");

		C1.request(2); // Request review-01 
		C2.request(1); // Request handin-01
		C3.request(2); // Request review-01
		C1.request(4); // Request reject-01
		C2.request(2); // Request review-01

		// All Clients request all tasks.
		for (int i=5 ; i>1 ; i--) {
		C1.request(--i);
		C2.request(++i);
		C3.request(i);
		}

	}


	private void request(int action) {
		sendBuffer = new byte[256];
		switch (action) {
		case 1:
			sendBuffer = "handin-01".getBytes(); 
			break;
		case 2:
			sendBuffer = "review-01".getBytes();
			break;
		case 3: 
			sendBuffer = "approve-01".getBytes();
			break;
		case 4: 
			sendBuffer = "reject-01".getBytes();
			break;
		case 5: 
			sendBuffer = "qualify-for-exam".getBytes();
			break;
		}

		packet = new DatagramPacket(sendBuffer, sendBuffer.length, address, this.port);

		try {
			socket.send(packet);

			System.out.println("Sending request: " + action);

			listen();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	

	}


	private static void listen() {
		recieveBuffer = new byte[256];
		packet = new DatagramPacket(recieveBuffer, recieveBuffer.length);
		try {
			socket.receive(packet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String recievedMessage  = new String(packet.getData());
		System.out.println("Recieved answer from server: ");
		System.out.println(recievedMessage + "\n");		
	}

}
